<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace app\api\controller\v13;

use app\api\controller\v2\Auth;
use app\common\cachemodel\FortuneCache;
use app\common\lib\astrolog\FortunesChange;
use app\common\lib\Util;
use app\common\model\AppLogicVersion;
use app\common\model\Orders;
use app\common\model\SystemLogicVersion;
use think\Env;

/**
 * 年运
 * Class FortuneForYear
 * @package app\api\controller\v7
 */
class FortuneForYear extends Auth
{
    protected $year_id;
    protected $active_switch;

    public function _initialize()
    {
        parent::_initialize();

        $this->year_id = config('goods.year_id');
        $this->active_switch = false;
//        $this->active_switch = checktime();
    }

    /**
     * 查看年运
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作');
        }

        $uid = (int)$this->user['id'];
        $rid = input('param.rid/d', 0);
        $year = input('param.year/d', 0);
        // 当前查看的时间
        $now_time = strtotime($year . '-1');
        // 参数验证
        if (!$uid || !$rid || strlen($year) !== 4 || !$now_time)
        {
            return show(config('code.error'), '未知操作');
        }

        // 日历显示时间范围
        $fortune_time_range = config('fortune.fortune_time_range');
        $range_start = $fortune_time_range['year']['start'];
        $range_end = $fortune_time_range['year']['end'];
        // 解锁状态
        $unlock_status = 0;
        $OrdersModel = new Orders();
        $recode_info = (new \app\common\cachemodel\Recode())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        $unlock_data = FortuneCache::getUnlockFortune($this->user['id'], $rid, 4);
        switch (true)
        {
            case in_array($now_time, $unlock_data['computing_fortune']):
                $unlock_status = 1;
                break;
            case in_array($now_time, $unlock_data['completed_fortune']):
                $unlock_status = 2;
                break;
        }
        $time_range = array_map(function ($timeValue)
        {
            return date('Y', $timeValue);
        }, $unlock_data['unlock_fortune']);

        // 统计订单人数
        $fortune_base_num = $OrdersModel->fortune_base(['type' => 2]);

        if ($unlock_status == 0)
        {
            $unlock_tips = [
                'title' => '年度报告解锁',
                'content' => '解锁当前运势，可查看你的' . $year . '年会发生什么，哪方面是今年的重点，它们是吉是凶，一整年又会有哪些起伏变化。（注意：解锁年运不包含月运）
一眼看穿365天，提前预知,早做安排。'
            ];
        } elseif ($unlock_status == 1)
        {
            $unlock_tips = [
                'title' => '年度报告计算等待中...',
                'content' => '由于年运的计算量较大,准了将在24小时内为您献上您所需要的年运。
小伙伴们耐心等待哦~',
            ];
        }
//        elseif ($unlock_status == 3)
//        {
//            $unlock_tips = [
//                'title' => '年运更新等待中...',
//                'content' => '由于年运正在重新计算中,准了将在24小时内为您献上您所需要的年运。',
//            ];
//        }
        else
        {
            $unlock_tips = [];
        }

        // 更新逻辑数据定义
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => 0
        ];

        // 用户计算成功后,获取年运信息及查询逻辑版本
        if ($unlock_status === 2)
        {
            // 获取年运信息
            $fortune = (new FortunesChange())->init($recode_info, $year, 'year', $this->headers['version']);
            /**
             * 1.7版本新增学业模块，低版本不返回该数据
             * 否则安卓端不显示年运曲线
             */
            $rec = Util::CheckAppVersion('1.7.0');
            if ($rec === '小')
            {
                if (count($fortune['fortune_year_change']) > 4)
                {
                    array_pop($fortune['fortune_year_change']);
                }
            }
            // 获取当前最新版本逻辑信息
            $SystemLogicModel = new SystemLogicVersion();
            $logic_data = $SystemLogicModel->getVersion(['type' => 3]);
            // 获取当前档案逻辑版本号
            $AppLogicModel = new AppLogicVersion();
            $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 3, 'time' => date('Y', $now_time)]);

            if ($user_logic)
            {
                // 若查看的时间版本号不是最新,提示更新
                if ($logic_data['version'] && $user_logic < $logic_data['version'])
                {
                    $update_logic = [
                        'title' => $logic_data['title'],
                        'content' => $logic_data['content'],
                        'status' => 1,
                    ];
                }
            } elseif (!$user_logic)
            {
                $update_logic = [
                    'title' => $logic_data['title'],
                    'content' => $logic_data['content'],
                    'status' => 1,
                ];
            }

            // 八字模块测试代码
//            $conclusion = (new Horoscope(['recode' => $recode_info,'advance'=>['year'=>$year]]))->yearConclusion();

            //过滤检测返回的列表，是否超过当前的日期
            $sort_arry = [];//排序数据
            if (isset($fortune['fortune_year_stage']))
            {
                $time_now = time();
                $year_now = date('Y') * 1;
                foreach ($fortune['fortune_year_stage'] as $k => $v)
                {
                    if (isset($v['end_time']))
                    {
                        /**
                         * 问题【1.是否只有今年才排序，过去的几年或者未来的几年都不处理；【过去几年置灰 未来不置灰】
                         * 2.未过期/已过期的时间排序 是按照 单个标题开始时间排序还是结束时间排序；【没过期的已过期都按照开始时间排序】
                         * 3.老版本的得分不变，新版本及以后大于1.9.6版本的分值变化为0~100区间；【同意】
                         * 4.词条修改 建议老版本和新版本都变化，因为主要修改的是 词条语句不通【同意】
                         * 小于当前年，都过期
                         */
                        if ($year < $year_now)
                        {
                            $v['is_expired'] = 1;
                        } else if ($year === $year_now)
                        {//等于当前年
                            $arr_time_end = date_parse_from_format('Y.m.d', $v['end_time']);
                            $time_end = mktime(23, 59, 59, $arr_time_end['month'], $arr_time_end['day'], $arr_time_end['year']);
                            $arr_time_start = date_parse_from_format('Y.m.d', $v['start_time']);
                            $time_start = mktime(23, 59, 59, $arr_time_start['month'], $arr_time_start['day'], $arr_time_start['year']);
                            if ($time_now > $time_end)
                            {
                                $v['is_expired'] = 1;
                            } else
                            {
                                $v['is_expired'] = 0;
                            }
                            $v['start_timestamp'] = $time_start;
                            //排序类型
                            $sort_arry['is_expired'][$k] = $v['is_expired'];
                            $sort_arry['start_timestamp'][$k] = $time_start;
                        } else
                        {//大于当前年，没过期
                            $v['is_expired'] = 0;
                        }
                        $fortune['fortune_year_stage'][$k] = $v;
                    }
                }

                //只有当前年才排序
                if ($year === $year_now)
                {
                    array_multisort($sort_arry['is_expired'], SORT_ASC, $sort_arry['start_timestamp'], SORT_ASC, $fortune['fortune_year_stage']);
                    //去掉 start_timestamp key
                    foreach ($fortune['fortune_year_stage'] as $k => $v)
                    {
                        if (isset($v['start_timestamp']))
                        {
                            unset($v['start_timestamp']);
                            $fortune['fortune_year_stage'][$k] = $v;
                        }
                    }
                }
            }
        } else
        {
            // 未解锁||解锁中 返回空值
            $fortune = [
                'fortune_year_change' => [],
                'fortune_year_stage' => [],
                'fortune_year_summarize' => [],
                'fortune_year_outline' => [],
            ];
        }

        $data = [
            'time' => $time_range,
            'fortune_year_summarize' => $fortune['fortune_year_summarize'],
            'fortune_year_outline' => $fortune['fortune_year_outline'],
            'fortune_year_change' => $fortune['fortune_year_change'],
            'fortune_year_stage' => $fortune['fortune_year_stage'],
            'unlock_num' => (int)($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
            'update_logic' => $update_logic,
            'unlock_tips' => $unlock_tips,
        ];

        // 活动开关，默认关闭
        $config = config('active.fortune_active');

        $host = Env::get('host.domain');

        $data['active_switch'] = [
            'day_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => '',
                'target' => 'link',
                'link' => $host . '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => $host . '/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active' => [
                'is_open' => false,
                'icon' => $config['icon'],
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => $host . '/web/fortune_year/active_details',//大礼包h5
            ]

        ];

        // 若未解锁并在活动时间内，开启
        if ($this->active_switch)
        {
            $data['active_switch']['day_active']['is_open'] = false;
            $data['active_switch']['month_active']['is_open'] = true;
            $data['active_switch']['year_active']['is_open'] = true;
        }

        return show(config('code.success'), '加载成功', $data);
    }
}
